package com.pig4cloud.pig.module.service.wx.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.common.core.exception.TransactionalException;
import com.pig4cloud.pig.common.core.util.LotteryUtil;
import com.pig4cloud.pig.common.core.util.OrderUtil;
import com.pig4cloud.pig.common.core.wx.WxAppPay;
import com.pig4cloud.pig.module.api.entity.CashActiveRole;
import com.pig4cloud.pig.module.api.entity.wx.UserRegCashRecord;
import com.pig4cloud.pig.module.api.entity.wx.WxPayTransaction;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.mapper.wx.UserRegCashRecordMapper;
import com.pig4cloud.pig.module.service.base.ICashActiveRoleService;
import com.pig4cloud.pig.module.service.wx.IUserRegCashRecordService;
import com.pig4cloud.pig.module.service.wx.IWxPayTransactionService;
import com.vdurmont.emoji.EmojiParser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 用户分享后得现金奖励的记录Service业务层处理
 *
 * @author ruoyi
 * @date 2022-06-10
 */
@Service
public class UserRegCashRecordServiceImpl extends ServiceImpl<UserRegCashRecordMapper, UserRegCashRecord> implements IUserRegCashRecordService {

	@Resource
	private UserRegCashRecordMapper regCashRecordMapper;
	@Resource
	private ICashActiveRoleService cashActiveRoleService;
	@Resource
	private UserRegCashRecordMapper cashRecordMapper;
	@Resource
	private IWxPayTransactionService payTransactionService;


	@Value("${web.appid}")
	private String appid;
	@Value("${web.appidMp}")
	private String appidMp;
	@Value("${web.secret}")
	private String secret;
	@Value("${web.secretMp}")
	private String secretMp;
	@Value("${web.mch_id}")
	private String mch_id;
	@Value("${web.api_key}")
	private String api_key;
	@Value("${web.keyPath}")
	private String keyPath;//微信支付的回调地址



	@Override
	public Page<UserRegCashRecord> selectRecordList(Page<UserRegCashRecord> page, Map<String, Object> map) {
		return regCashRecordMapper.selectRecordList(page,map);
	}

	@Override
	public Double selectCashMoney(Map<String, Object> map) {
		return regCashRecordMapper.selectCashMoney(map);
	}

	@Override
	public List<UserRegCashRecord> selectRecordListExport(Map<String, Object> map) {
		return regCashRecordMapper.selectRecordListExport(map);
	}

	@Override
	public UserRegCashRecord getRecordByMerCheck(int merId, int userId) {
		QueryWrapper<UserRegCashRecord> qw = new QueryWrapper<>();
		qw.eq("record_type",1);
		qw.eq("pay_state",1);
		qw.eq("user_id",userId);
		qw.eq("reg_mer_id",merId);
		return regCashRecordMapper.selectOne(qw);
	}


	/**
	 *  新用户邀请现金奖励的 中奖规则
	 * @param activeRoles
	 * @return
	 */
	public static List<Double> drawRegCashRecord(List<CashActiveRole> activeRoles){
		List<Double> orgProbList = new ArrayList<>();
		if(null != activeRoles && activeRoles.size()>0){
			orgProbList = new ArrayList<>(activeRoles.size());
			for(CashActiveRole role:activeRoles){
				//按顺序将概率添加到集合中
				orgProbList.add(role.getRateProbability());
			}
		}
		return orgProbList;
	}

	/**
	 *  领取现金奖励
	 * @param user
	 * @param regUserId
	 * @return
	 */
	@Override
	@Transactional
	public int addCashRecord(WxUser user, int regUserId, int record_type) {
		int ret = 0;
		try{
			UserRegCashRecord cashRecord = new UserRegCashRecord();
			cashRecord.setRecordType(record_type);
			double cashMoney = 0d;
			QueryWrapper<CashActiveRole> qw = new QueryWrapper<>();
			qw.eq("cash_type",record_type);
			qw.eq("state",1);
			List<CashActiveRole> activeRoles = cashActiveRoleService.list(qw);
			if(CollUtil.isNotEmpty(activeRoles)){
				List<Double> list = drawRegCashRecord(activeRoles);
				LotteryUtil ll = new LotteryUtil(list);
				int index = ll.randomColumnIndex();
				CashActiveRole activeRole = activeRoles.get(index);
				if(activeRole!=null){
					if(activeRole.getIsRange() == 1){
						cashMoney = LotteryUtil.getValueByRandom(activeRole.getMinMoney().doubleValue(),activeRole.getMaxMoney().doubleValue());
					}else{
						cashMoney = activeRole.getMaxMoney().doubleValue();
					}
					System.out.println("奖励金额： " + cashMoney);
					cashRecord.setCashActiveId(activeRole.getId());
				}
			}

			if(cashMoney > 0){
				cashRecord.setCreateTime(new Date());
				cashRecord.setUserId(user.getId());
				cashRecord.setOpenId(user.getOpenId());
				if(record_type == 0){
					cashRecord.setRegUserId(regUserId);
				}else{
					cashRecord.setRegMerId(regUserId);
				}
				cashRecord.setCashMoney(new BigDecimal(cashMoney));
				cashRecord.setPayState(0);
				ret = cashRecordMapper.insert(cashRecord);
				if(ret <= 0){
					throw new TransactionalException("cashRecordMapper system error");
				}

				String tradeNo = OrderUtil.getPayNo();
				cashRecord.setTradeNo(tradeNo);

				String remark = "邀请新用户奖励";
				if(record_type == 1){
					remark = "邀请新商家入驻奖励";
				}
				WxAppPay wxAppPay = new WxAppPay("", secret, appid, mch_id,api_key);
				Map<String, String> retRequest = wxAppPay.weixinChangePay(cashRecord.getTradeNo(),cashRecord.getCashMoney(),cashRecord.getOpenId(),keyPath,remark);
				if(retRequest.containsKey("return_code")){
					String result_code = retRequest.get("result_code");
					String err_code_des = retRequest.containsKey("err_code_des") ? retRequest.get("err_code_des") : "";
					cashRecord.setResultCode(result_code);
					if(result_code.equals("SUCCESS")){
						cashRecord.setPayState(1);//支付成功

						// 添加 微信支付的 动账记录
						WxPayTransaction transaction = new WxPayTransaction();
						transaction.setPayType(0);// 0 -微信支付
						transaction.setTransactionId(cashRecord.getTradeNo());
						transaction.setUserId(user.getId());
						transaction.setFeeType("mer_reg");
						transaction.setTotalMoney(cashRecord.getCashMoney());
						if(StrUtil.isNotEmpty(user.getNickName())){
							transaction.setNickName(EmojiParser.parseToAliases(user.getNickName()));
						}
						transaction.setCreateTime(new Date());
						transaction.setInOrOut(0);//动账  0 - 出账 1 - 进账
						transaction.setRemark(remark);
						payTransactionService.save(transaction);


					}else{
						cashRecord.setPayState(2);//支付失败
						cashRecord.setErrCodeDes(err_code_des);
					}
					String pay_str = retRequest.get("pay_str");
					String reback_str = retRequest.get("reback_str");
					cashRecord.setPayStr(pay_str);
					cashRecord.setRebackStr(reback_str);

					ret = cashRecordMapper.updateById(cashRecord);
					if(ret <= 0){
						throw new TransactionalException("cashRecordMapper system error");
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
			throw new TransactionalException("addCashRecord system error");
		}
		return ret;
	}

}
